package com.kpmg.questionnaire.service.impl;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.kpmg.questionnaire.model.AnswerEntity;
import com.kpmg.questionnaire.model.EmailEntity;
import com.kpmg.questionnaire.model.QuestionEntity;
import com.kpmg.questionnaire.model.UserEntity;
import com.kpmg.questionnaire.service.IEmailService;
import com.kpmg.questionnaire.utils.FreemarkerUtils;
import com.kpmg.questionnaire.utils.WebConstants;
import com.sun.mail.util.MailSSLSocketFactory;

import freemarker.core.ParseException;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;

/**
 * Created by xionghao on 2016/11/12.
 */
@Service
public class EmailServiceImpl implements IEmailService {

	// private static Logger logger = Logger.getLogger(EmailServiceImpl.class);

	@Autowired
	private JavaMailSender javaMailSender;

	@Autowired
	private MailSSLSocketFactory sslSocketFactory;

	// @Resource
	// private SimpleMailMessage simpleMailMessage;

	@Value("${mail.username}")
	private String mailUserName;
	
	private static final SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

	@Override
	public void emailManage() {
		EmailEntity mail = new EmailEntity();
		// 主题
		mail.setSubject("清单");

		// 内容
		StringBuilder builder = new StringBuilder();
		builder.append("<html><body>你好！<br />");
		builder.append("&nbsp&nbsp&nbsp&nbsp附件是个人清单。<br />");
		builder.append("&nbsp&nbsp&nbsp&nbsp其中人信息；<br />");
		builder.append("</body></html>");
		String content = builder.toString();

		mail.setContent(content);

		// sendEmail(mail);
	}

	@Override
	public void sendEvaluationResultsEmail(AnswerEntity answerEntity, List<QuestionEntity> questions, String realPath,
			UserEntity userEntity) {
		String[] arrAnswer = answerEntity.getContent().split(",");
		// 邮件发送
		EmailEntity mail = new EmailEntity();
		mail.setSubject("Accounting Change Readiness");
		mail.setToEmails(answerEntity.getUserId());
		mail.setToAddresses(answerEntity.getUserId());

		String baseTemplatePath = null;
		try {
			Resource res = new ClassPathResource("META-INF/ftl/email.ftl");
			String absolutePath = res.getFile().getAbsolutePath();
			baseTemplatePath = absolutePath.replaceAll("/email.ftl", "");

			Map<String, Object> mailData = new HashMap<String, Object>();
			mailData.put("nickname", userEntity.getFirstName() + " " + userEntity.getLastName());
			mailData.put("title", answerEntity.getTitle());
			mailData.put("result", answerEntity.getResults());
			mailData.put("evaluationDate", sdf.format(new Date()));
			String mailContent = FreemarkerUtils.parseTemplate(baseTemplatePath, "email.ftl", mailData);
			mail.setContent(mailContent);

			final String pdfDir = realPath + "/" + userEntity.getId();
			final File pdfDirectory = new File(pdfDir);
			if (!pdfDirectory.exists()) {
				pdfDirectory.mkdirs();
			}
			String fileName = String.format("%s/%d.pdf", pdfDir, System.currentTimeMillis());

			Map<String, Object> data = new HashMap<String, Object>();
			data.put("title", answerEntity.getTitle());
			data.put("questions", questions);
			data.put("answerContents", arrAnswer);
			String html = FreemarkerUtils.parseTemplate(baseTemplatePath, "confirm.ftl", data);
			File pdfFile = new File(fileName);
			Document document = new Document();
			FileOutputStream fos = new FileOutputStream(pdfFile);
			PdfWriter writer = PdfWriter.getInstance(document, fos);
			document.open();
			InputStream in = new ByteArrayInputStream(html.getBytes());
			XMLWorkerHelper.getInstance().parseXHtml(writer, document, in);
			document.close();
			this.sendEmail(mail, pdfFile);
		} catch (TemplateNotFoundException e) {
			e.printStackTrace();
		} catch (MalformedTemplateNameException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 发送邮件
	 *
	 * @throws Exception
	 * @author chenyq
	 * @date 2016-5-9 上午11:18:21
	 */
	@Override
	public void sendEmail(EmailEntity mail, File file) throws Exception {
		// 建立邮件消息
		MimeMessage message = javaMailSender.createMimeMessage();

		MimeMessageHelper messageHelper;
		try {
			messageHelper = new MimeMessageHelper(message, true, "UTF-8");
			// 设置发件人邮箱
			messageHelper.setFrom(mailUserName);
			// 设置收件人邮箱
			if (!StringUtils.isEmpty(mail.getToEmails())) {
				String[] toEmailArray = mail.getToEmails().split(";");
				if(0 <= toEmailArray.length){
					messageHelper.setTo(toEmailArray);
				}else{
					messageHelper.setTo(mail.getToEmails());
				}
			}else{
				throw new Exception("Recipient cannot be empty ！");
			}
			// 邮件主题
			messageHelper.setSubject(mail.getSubject());
			// true 表示启动HTML格式的邮件
			messageHelper.setText(mail.getContent(), true);
			FileSystemResource fileResource = new FileSystemResource(file);
			messageHelper.addAttachment("Accounting Change Readiness.pdf", fileResource);
			messageHelper.setSentDate(new Date());
			// 发送邮件
			javaMailSender.send(message);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}

}
